import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/order_confirm.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tobias/tobias.dart' as tobias;

class OrderCheckoutModel extends ViewModel {
  final Api api;
  Address _address;
  Map<int, String> _orderMemo = {};
  String _errorMessage;

  OrderCheckoutModel(this.api) : super();

  Address get address => _address;

  set address(Address value) {
    _address = value;
    notifyListeners();
  }

  void setOrderMemo(int storeId, String memo) {
    _orderMemo[storeId] = memo;
  }

  String get errorMessage => _errorMessage;

  Future<ViewState> orderCheckout(
    int addressId,
    String payType,
    Map<String, int> storeCarts,
  ) async {
    viewState = ViewState.busy;
    try {
      if (addressId == null) {
        throw '请选择收货地址';
      }
      // 获取服务器签名信息
      Map<String, String> other = _orderMemo.map((key, value) => MapEntry('orderMemo_$key', value));
      dynamic _signResult = await api.orderCheckout(addressId, payType, storeCarts, other);
      // 发起支付
      switch (payType) {
        case 'WX_PAY':
          // 微信支付
          Map<String, dynamic> signResult = _signResult;
          Map<dynamic, dynamic> payResult = await fluwx.payWithWeChat(
            appId: signResult['appid'].toString(),
            partnerId: signResult['partnerid'].toString(),
            prepayId: signResult['prepayid'].toString(),
            packageValue: signResult['package'].toString(),
            nonceStr: signResult['noncestr'].toString(),
            timeStamp: int.tryParse(signResult['timestamp']),
            sign: signResult['sign'].toString(),
          );
          debugPrint('wxPay payResult = $payResult');
          // 判断支付结果
          if (!payResult['result']) {
            throw '支付失败';
          }
          var response = await fluwx.responseFromPayment.first.timeout(Duration(minutes: 1));
          debugPrint('response errCode = ${response.errCode}, errStr = ${response.errStr}');
          if (response.errCode != 0) {
            throw '支付失败';
          }
          break;
        case 'ALI_PAY':
          // 支付宝支付
          String signResult = _signResult;
          Map<dynamic, dynamic> payResult = await tobias.aliPay(signResult);
          debugPrint('aliPay payResult = $payResult');
          // 判断支付结果
          if (payResult['resultStatus'].toString() != '9000') {
            throw payResult['memo'].toString() ?? '支付失败';
          }
          break;
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
